package com.hmall.order.task;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmall.common.client.ItemClient;
import com.hmall.common.pojo.Item;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description ItemTask
 * @Author GGBond
 * @Date 2024-11-16
 */

@Component
public class OrderTask {

    @Autowired
    private IOrderDetailService orderDetailServiceService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ItemClient itemClient;

    //@Scheduled(fixedRate = 60000)
    public void doTask(){
        List<Order> orderList = orderService.list(Wrappers.<Order>lambdaQuery()
                .eq(Order::getStatus, 1)
                .le(Order::getCloseTime, LocalDateTime.now()));
        List<OrderDetail> orderDetailList=new ArrayList<>();
        if(CollectionUtils.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                OrderDetail orderDetail = orderDetailServiceService.getById(order.getId());
                orderDetailList.add(orderDetail);
                order.setStatus(5);
                Item item = itemClient.getById(orderDetail.getItemId());
                item.setStock(orderDetail.getNum() + item.getStock());
                item.setSold(item.getSold() - orderDetail.getNum());
                itemClient.updateItem(item);
            }
            orderService.updateBatchById(orderList);
        }
    }
}
